package com.mdd.front.service.impl.yangyangLeadingEnterprise;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.mdd.common.core.PageResult;
import com.mdd.common.entity.yangyangLeadingEnterprise.TAppEnterprise;
import com.mdd.common.entity.yangyangLeadingEnterprise.TAppUserData;
import com.mdd.common.entity.yangyangLeadingEnterprise.common.JsonReturn;
import com.mdd.common.mapper.yangyangLeadingEnterprise.TAppEnterpriseMapper;
import com.mdd.common.mapper.yangyangLeadingEnterprise.TAppUserDataMapper;
import com.mdd.common.util.TimeUtils;
import com.mdd.front.service.yangyangLeadingEnterprise.ITAppEnterpriseService;
import com.mdd.front.validate.common.PageValidate;
import com.mdd.front.validate.yangyangLeadingEnterprise.TAppEnterpriseCreateValidate;
import com.mdd.front.validate.yangyangLeadingEnterprise.TAppEnterpriseSearchValidate;
import com.mdd.front.validate.yangyangLeadingEnterprise.TAppEnterpriseUpdateValidate;
import com.mdd.front.vo.yangyangLeadingEnterprise.TAppEnterpriseDetailVo;
import com.mdd.front.vo.yangyangLeadingEnterprise.TAppEnterpriseListedVo;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import javax.annotation.Resource;
import java.util.*;

/**
 * 【请填写功能名称】实现类
 * @author LikeAdmin
 */
@Service
public class TAppEnterpriseServiceImpl implements ITAppEnterpriseService {
        
    @Resource
    TAppEnterpriseMapper tAppEnterpriseMapper;

    @Resource
    TAppUserDataMapper appUserDataMapper;

    /**
     * 【请填写功能名称】列表
     *
     * @author LikeAdmin
     * @param pageValidate 分页参数
     * @param searchValidate 搜索参数
     * @return PageResult<TAppEnterpriseListedVo>
     */
    @Override
    public PageResult<TAppEnterpriseListedVo> list(PageValidate pageValidate, TAppEnterpriseSearchValidate searchValidate) {
        Integer page  = pageValidate.getPage_no();
        Integer limit = pageValidate.getPage_size();

        QueryWrapper<TAppEnterprise> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByDesc("id");

        tAppEnterpriseMapper.setSearch(queryWrapper, searchValidate, new String[]{
            "like:enterpriseName@enterprise_name:str",
            "=:enterpriseLegalPerson@enterprise_legal_person:str",
            "=:enterpriseTaxNumber@enterprise_tax_number:str",
            "=:enterpriseRegisteredAddress@enterprise_registered_address:str",
            "=:businessIntrodution@business_introdution:str",
            "=:contactInformation@contact_information:str",
            "=:userId@user_id:int",
        });

        IPage<TAppEnterprise> iPage = tAppEnterpriseMapper.selectPage(new Page<>(page, limit), queryWrapper);

        List<TAppEnterpriseListedVo> list = new LinkedList<>();
        for(TAppEnterprise item : iPage.getRecords()) {
            TAppEnterpriseListedVo vo = new TAppEnterpriseListedVo();
            BeanUtils.copyProperties(item, vo);
            vo.setCreateTime(TimeUtils.timestampToDate(item.getCreateTime().getTime()));
            vo.setUpdateTime(TimeUtils.timestampToDate(item.getUpdateTime().getTime()));
            list.add(vo);
        }

        return PageResult.iPageHandle(iPage.getTotal(), iPage.getCurrent(), iPage.getSize(), list);
    }

    /**
     * 【请填写功能名称】详情
     *
     * @author LikeAdmin
     * @param id 主键参数
     * @return TAppEnterprise
     */
    @Override
    public TAppEnterpriseDetailVo detail(Integer id) {
        TAppEnterprise model = tAppEnterpriseMapper.selectOne(
                new QueryWrapper<TAppEnterprise>()
                    .eq("id", id)
                    .last("limit 1"));

        Assert.notNull(model, "数据不存在");

        TAppEnterpriseDetailVo vo = new TAppEnterpriseDetailVo();
        BeanUtils.copyProperties(model, vo);
        return vo;
    }

    /**
     * 【请填写功能名称】新增
     *
     * @author LikeAdmin
     * @param createValidate 参数
     */
    @Override
    public void add(TAppEnterpriseCreateValidate createValidate) {
        TAppEnterprise model = new TAppEnterprise();
        model.setEnterpriseName(createValidate.getEnterpriseName());
        model.setEnterpriseLegalPerson(createValidate.getEnterpriseLegalPerson());
        model.setEnterpriseTaxNumber(createValidate.getEnterpriseTaxNumber());
        model.setEnterpriseRegisteredAddress(createValidate.getEnterpriseRegisteredAddress());
        model.setBusinessIntrodution(createValidate.getBusinessIntrodution());
        model.setContactInformation(createValidate.getContactInformation());
        model.setUserId(Long.valueOf(createValidate.getUserId()));
        model.setCreateTime(new Date());
        model.setUpdateTime(new Date());
        tAppEnterpriseMapper.insert(model);
    }

    /**
     * 【请填写功能名称】编辑
     *
     * @author LikeAdmin
     * @param updateValidate 参数
     */
    @Override
    public void edit(TAppEnterpriseUpdateValidate updateValidate) {
        TAppEnterprise model = tAppEnterpriseMapper.selectOne(
                new QueryWrapper<TAppEnterprise>()
                    .eq("id",  updateValidate.getId())
                    .last("limit 1"));

        Assert.notNull(model, "数据不存在!");

        model.setId(updateValidate.getId());
        model.setEnterpriseName(updateValidate.getEnterpriseName());
        model.setEnterpriseLegalPerson(updateValidate.getEnterpriseLegalPerson());
        model.setEnterpriseTaxNumber(updateValidate.getEnterpriseTaxNumber());
        model.setEnterpriseRegisteredAddress(updateValidate.getEnterpriseRegisteredAddress());
        model.setBusinessIntrodution(updateValidate.getBusinessIntrodution());
        model.setContactInformation(updateValidate.getContactInformation());
        model.setUserId(Long.valueOf(updateValidate.getUserId()));
        model.setUpdateTime(new Date());
        tAppEnterpriseMapper.updateById(model);
    }

    /**
     * 【请填写功能名称】删除
     *
     * @author LikeAdmin
     * @param id 主键ID
     */
    @Override
    public void del(Integer id) {
        TAppEnterprise model = tAppEnterpriseMapper.selectOne(
                new QueryWrapper<TAppEnterprise>()
                    .eq("id", id)
                    .last("limit 1"));

        Assert.notNull(model, "数据不存在!");

        tAppEnterpriseMapper.delete(new QueryWrapper<TAppEnterprise>().eq("id", id));
    }

    /**
     * 根据id查询企业信息
     * @param enterpriseId
     * @return
     */
    @Override
    public TAppEnterprise selectEnterpriseById(Integer enterpriseId) {
        TAppEnterprise appEnterprise = tAppEnterpriseMapper.selectById(enterpriseId);
        return appEnterprise;
    }

    /**
     * 查询用户名下企业/用户企业下拉列表
     * @param userId
     * @return
     */
    @Override
    public List<TAppEnterprise> selectEnterpriseListByUserId(Integer userId) {
        List<TAppEnterprise> appEnterpriseList = tAppEnterpriseMapper.selectList(new QueryWrapper<TAppEnterprise>().eq("user_id", userId));
        return Optional.ofNullable(appEnterpriseList).orElse(new ArrayList<>());
    }

    /**
     * 用户绑定新的企业信息
     * @param appEnterprise
     * @return
     */
    @Override
    public String insertEnterpriseByUserId(TAppEnterprise appEnterprise) {
        Long userId = appEnterprise.getUserId();
        String enterpriseName = appEnterprise.getEnterpriseName();
        if(userId == null || enterpriseName == null) {
            return JsonReturn.fail("必传参数不能为空",201).toJsonStr();
        }
        tAppEnterpriseMapper.insert(appEnterprise);

        //更新用户最近的企业信息
        TAppUserData appUserData = appUserDataMapper.selectOne(new QueryWrapper<TAppUserData>().eq("user_id", userId));
        if(appUserData != null && appUserData.getId() != null) {
            appUserData.setEnterpriseId(appEnterprise.getId());
            appUserDataMapper.updateById(appUserData);
        }
        return JsonReturn.success().toJsonStr();
    }

}
